package com.example.hookapp.utils;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by xx on 2018/9/9
 * description：延迟执行任务工具
 */
public class ThreadUtils {
    private static final int THREAD_POOL_SIZE = 5;
    private static ExecutorService EXECUTOR = null;

    public static Disposable post(int delayTime, final Runnable runnable) {
        return Observable.timer(delayTime, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        if (runnable != null) {
                            runnable.run();
                        }
                    }
                });
    }

    public static Disposable post(final Runnable runnableOnThread, final Runnable runnableOnUi) {
        return Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> e) throws Exception {
                if (runnableOnThread != null) {
                    runnableOnThread.run();
                }
                e.onNext("");
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (runnableOnUi != null) {
                            runnableOnUi.run();
                        }
                    }
                });
    }

    private static void init() {
        if (EXECUTOR == null) {
            synchronized (ThreadUtils.class) {
                if (EXECUTOR == null) {
                    EXECUTOR = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
                }
            }
        }
    }

    public static void runOnThread(Runnable runnable) {
        init();
        EXECUTOR.submit(runnable);
    }

    public static void runOnUiThread(final Runnable runnable) {
        Observable.just(1).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) throws Exception {
                if (runnable != null) {
                    runnable.run();
                }
            }
        });
    }

    public static void sleep(long mills){
        try {
            Thread.sleep(mills);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
